package com.ethink.platform.job;

import cn.hutool.core.lang.Pair;
import com.ethink.order.api.JkyTradeLogFacade;
import com.ethink.order.api.request.JkyTradeLogUpdateCkFlagRequest;
import com.ethink.order.api.request.JkyTradeLogUpdateErrorRequest;
import com.ethink.order.api.response.JkyTradeLogGetDetailResponse;
import com.ethink.platform.manager.SaleOrderManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class JackyunTradeOrderProcessingJob {

    @Autowired
    private JkyTradeLogFacade jkyTradeLogFacade;

    @Autowired
    private SaleOrderManager saleOrderManager;


    @XxlJob("JackyunTradeOrderProcessingJob")
    public void run() {
        log.info("====================== 吉客云销售单出库任务开始执行 ======================");
        JkyTradeLogGetDetailResponse jkyTradeLogGetDetailResponse = jkyTradeLogFacade.topOneProcessingJkyTradeLog();
        while (jkyTradeLogGetDetailResponse != null) {
            JkyTradeLogUpdateCkFlagRequest jkyTradeLogUpdateCkFlagRequest = new JkyTradeLogUpdateCkFlagRequest();
            jkyTradeLogUpdateCkFlagRequest.setId(jkyTradeLogGetDetailResponse.getJkyTradeLogInfo().getId());
            try {
                // 执行出库操作
                Pair<Boolean, String> result = saleOrderManager.saleAdd4(jkyTradeLogGetDetailResponse.getJkyTradeLogInfo(), jkyTradeLogGetDetailResponse.getJkyTradeLogDetailInfoList());
                jkyTradeLogUpdateCkFlagRequest.setCkFlag(result.getKey());
                jkyTradeLogUpdateCkFlagRequest.setIsError(StringUtils.isNotBlank(result.getValue()));
                jkyTradeLogUpdateCkFlagRequest.setRemark(result.getValue());
            } catch (Exception e) {
                log.error("处理失败", e);
                jkyTradeLogUpdateCkFlagRequest.setCkFlag(true);
                jkyTradeLogUpdateCkFlagRequest.setIsError(true);
                jkyTradeLogUpdateCkFlagRequest.setRemark(e.getMessage());
            }
            jkyTradeLogFacade.updateJkyTradeLogCkFlag(jkyTradeLogUpdateCkFlagRequest);

            jkyTradeLogGetDetailResponse = jkyTradeLogFacade.topOneProcessingJkyTradeLog();
        }
        log.info("====================== 吉客云销售单出库任务执行结束 ======================");
    }
}
